const express = require('express')
const app = express()
const cors = require('cors')
const joi = require('joi')

app.use(cors())
app.use(express.urlencoded({ extended: false }))
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


//使用express.static内置中间件，可以进行静态资源托管，可以用tmp_uploads下的图片读取
app.use('/tmp_uploads', express.static('tmp_uploads'))

// 导入配置文件
const config = require('./config')

// 解析 token 的中间件
const expressJWT = require('express-jwt')

// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\/private\/v1\/reg/, /^\/api\/private\/v1\/login/, /^\/api\/private\/v1\/goods/, /^\/api\/private\/v1\/city/, /^\/api\/private\/v1\/orders/, /^\/api\/private\/v1\/declerks/], }))

app.use((req, res, next) => {
    res.ResData = function(err, status = 1, data = {}) {
        res.send({
            data,
            meta: {
                status,
                msg: err
            }
        })
    }
    next()
})

const userRouter = require('./router/user.js')
app.use('/api/private/v1', userRouter)
const menuRouter = require('./router/menu.js')
app.use('/api/private/v1', menuRouter)
const managerRouter = require('./router/manager.js')
app.use('/api/private/v1', managerRouter)
const cityRouter = require('./router/city.js')
app.use('/api/private/v1', cityRouter)
const orderRouter = require('./router/order.js')
app.use('/api/private/v1', orderRouter)
const goodListRouter = require('./router/goodList.js')
app.use('/api/private/v1', goodListRouter)
const declerkRouter = require('./router/declerk.js')
app.use('/api/private/v1', declerkRouter)
const authorizationRouter = require('./router/authorization.js')
app.use('/api/private/v1', authorizationRouter)
const categoryRouter = require('./router/category.js')
app.use('/api/private/v1', categoryRouter)

// 错误中间件
app.use(function(err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.send(err)
        // 未知错误
    res.send(err)
})


//错误中间件
app.use(function(err, req, res, next) {
    // 省略其它代码...

    // 捕获身份认证失败的错误
    if (err.name === 'UnauthorizedError') return res.send({ status: 3, error: '身份认证失败' })

    // 未知错误...
})

app.listen(8888, function() {
    console.log('success')
})